package cn.com.taiji.oospub.wechat.common.tool;

import cn.com.taiji.oospub.wechat.common.wxpay.pay.Configure;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ImgSaveTools {
	   

	  public  File fetchTmpFile(String media_id, String type,String token){
		  try {
		//       String token = AccessTokenApi.getAccessToken().getAccessToken();
		       String url = null;
		   //视频是http协议
		   if("video".equalsIgnoreCase(type)){
			   url = String.format(Configure.requestGetMidia_Video, token, media_id);
		   }else{
			   url = String.format(Configure.requestGetMidia2, token, media_id);
		   }
		   URL u = new URL(url);
		   HttpURLConnection  conn = (HttpURLConnection) u.openConnection();
		   conn.setRequestMethod("GET");
		   conn.connect();
		   BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
		   String content_disposition = conn.getHeaderField("content-disposition");
		   System.out.println("content_disposition-----"+content_disposition);
		   
		   //微信服务器生成的文件名称
		   String file_name ="";
		   String[] content_arr = content_disposition.split(";");
		   if(content_arr.length  == 2){
		    String tmp = content_arr[1];
		    int index = tmp.indexOf("\"");
		    file_name =tmp.substring(index+1, tmp.length()-1);
		    System.out.println("file_name-----"+file_name);
		   }
		   //生成不同文件名称
		   File file = new File(file_name);
		   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
		   byte[] buf = new byte[2048];
		   int length = bis.read(buf);
		   while(length != -1){
		    bos.write(buf, 0, length);
		    length = bis.read(buf);
		   }
		   bos.close();
		   bis.close();
		   return file;
		 } catch (MalformedURLException e) {
		  e.printStackTrace();
		 } catch (IOException e) {
		  e.printStackTrace();
		 }
		 return null;
	 }

	  public InputStream getInputStream(String accessToken, String mediaId) {  
	      InputStream is = null;  
	      String url = Configure.requestGetMidia;
	      url = url.replace("ACCESS_TOKEN", accessToken);
	      url = url.replace("MEDIA_ID", mediaId); 
	      try {  
	          URL urlGet = new URL(url);  
	          HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
	          http.setRequestMethod("GET"); // 必须是get方式请求  
	          http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
	          http.setDoOutput(true);  
	          http.setDoInput(true);  
	          System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒  
	          System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒  
	          http.connect();  
	          // 获取文件转化为byte流  
	          is = http.getInputStream();  
	      } catch (Exception e) {  
//	          LOGGER.error("Failed to convert inputStream from weixin server,accessToken:{},mediaId:{}",accessToken,mediaId);
	      }  
	      return is;  

	  }  
	  
	  public void saveImageToDisk(String mediaId, String picName, String picPath,String token) throws Exception {  
	      String accessToken = token;
	      InputStream inputStream = getInputStream(accessToken, mediaId); 
	      
	      // 循环取出流中的数据
	      byte[] data = new byte[1024];  
	      int len = 0;  
	      FileOutputStream fileOutputStream = null;  
	      try {  
	          fileOutputStream = new FileOutputStream(picPath+picName+".jpg");  
	          while ((len = inputStream.read(data)) != -1) {  
	              fileOutputStream.write(data, 0, len);  
	          }  
//	          LOGGER.info("Write the fileInputStream is successful");
	      } catch (IOException e) {  
//	          LOGGER.error("Write the fileInputStream is error");
	      } finally {  
	          if (inputStream != null) {  
	              try {  
	                  inputStream.close();  
	              } catch (IOException e) {  
//	                  LOGGER.error("Close the fileInputStream is error");
	              }  
	          }  
	          if (fileOutputStream != null) {  
	              try {  
	                  fileOutputStream.close();  
	              } catch (IOException e) {  
//	                  LOGGER.error("Close the fileOutputStream is error");
	              }  
	          }  
	      }  
	  }
}
